import os
import pandas as pd
import re

count = 0

prefix = 'D:/project/SCMP/scmp-coding231019/trunk/'
project_tuple = (
    'psc-parent', 'scmp-accounting-parent', 'scmp-charging-parent', 'scmp-charging-rt-parent', 'scmp-check-parent',
    'scmp-collect-parent', "scmp-contract-parent", 'scmp-manage-parent', 'scmp-parent', 'scmp-provider-parent',
    'scmp-settlement-parent')

data2 = {'project_name': [], 'expClass': [], 'code': [], 'errMsg': [], 'line':[]}


def list_files(project_name):
    err_msg_patan = r'"(.*)"'
    # *加? 表示是非贪婪模式
    exp_class_patan = r'new (.*?)\('
    data = {'class': [], 'line': [], 'exception': [], 'errMsg': []}
    """
    列出指定文件夹下的所有文件和子文件夹。
    """
    dir_path = prefix + project_name
    for root, dirs, files in os.walk(dir_path):
        level = root.replace(dir_path, '').count(os.sep)
        indent = ' ' * 4 * (level)
        # print('{}{}/'.format(indent, os.path.basename(root)))
        subindent = ' ' * 4 * (level + 1)

        for fileName in files:
            if not 'Exception' in fileName and fileName.endswith('.java') and not fileName.endswith('Test.java'):
                # print('{}{}'.format(subindent, fileName))
                with open(root + '/' + fileName, 'r', encoding='utf-8') as file:
                    line_no = 0
                    for line in file:
                        line_no += 1
                        if 'throw ' in line or 'Throw' in line or 'exceptionally' in line and not 'catch' in line:
                            # print(line.strip())
                            data['class'].append(fileName)
                            data['line'].append(line_no)
                            data['exception'].append(line.strip())
                            match1 = re.search(err_msg_patan, line)
                            match2 = re.search(exp_class_patan, line)
                            if match1 and match2:
                                err_msg = match1.group(1)
                                exp_class = match2.group(1)
                                data['errMsg'].append(err_msg)
                                if not line.strip() in data2['line']:
                                    data2['project_name'].append(project_name)
                                    lst = err_msg.replace('"', '').split(",")
                                    if len(lst) > 1 and lst[0].isdigit():
                                        data2['code'].append(lst[0])
                                        data2['errMsg'].append(lst[1].strip())
                                    else:
                                        data2['code'].append('')
                                        data2['errMsg'].append(err_msg.strip())
                                    data2['expClass'].append(exp_class)
                                    data2['line'].append(line.strip())
                            else:
                                data['errMsg'].append('')

    return data


for project_name in project_tuple:
    data = list_files(project_name)
    df = pd.DataFrame(data)
    with pd.ExcelWriter('example.xlsx', engine='openpyxl', mode='a') as writer:
        df.to_excel(writer, sheet_name=project_name, index=False)

df = pd.DataFrame(data2)
with pd.ExcelWriter('example2.xlsx', engine='openpyxl', mode='a') as writer:
    df.to_excel(writer, sheet_name="Sheet1", index=False)
